#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2022/10/9 17:09 
# @File           : tools.py
# @IDE            : PyCharm
# @desc           : 工具类

import datetime
import json
import random
import string
from typing import List, Union, Optional
import importlib
from core.logger import logger
import pystache


def list_dict_find(options: List[dict], key: str, value: any) -> Union[dict, None]:
    """
    字典列表查找
    """
    return next((item for item in options if item.get(key) == value), None)


def generate_string(length: int = 8) -> str:
    """
    生成随机字符串
    :param length: 字符串长度
    """
    return ''.join(random.sample(string.ascii_letters + string.digits, length))


def import_modules(modules: list, desc: str, **kwargs):
    for module in modules:
        if not module:
            continue
        try:
            # 动态导入模块
            module_pag = importlib.import_module(module[0:module.rindex(".")])
            getattr(module_pag, module[module.rindex(".") + 1:])(**kwargs)
        except ModuleNotFoundError:
            logger.error(f"AttributeError：导入{desc}失败，未找到该模块：{module}")
        except AttributeError:
            logger.error(f"ModuleNotFoundError：导入{desc}失败，未找到该模块下的方法：{module}")


async def import_modules_async(modules: list, desc: str, **kwargs):
    for module in modules:
        if not module:
            continue
        try:
            # 动态导入模块
            module_pag = importlib.import_module(module[0:module.rindex(".")])
            await getattr(module_pag, module[module.rindex(".") + 1:])(**kwargs)
        # except TimeoutError:
        #     logger.error(f"asyncio.exceptions.TimeoutError：连接Mysql数据库超时")
        #     print(f"asyncio.exceptions.TimeoutError：连接Mysql数据库超时")
        except ModuleNotFoundError:
            logger.error(f"AttributeError：导入{desc}失败，未找到该模块：{module}")
        except AttributeError:
            logger.error(f"ModuleNotFoundError：导入{desc}失败，未找到该模块下的方法：{module}")


def render_config(config: dict, mapping: Optional[dict] = None):
    if not mapping:
        mapping = {}
    mapping = {k : v for k, v in mapping.items() if v is not None}
    config_str = json.dumps(config)
    config_str = pystache.render(config_str, mapping)
    return json.loads(config_str)

def filter_config(config_dict: dict):
    config = {}
    for k, v in config_dict.items():
        if v is None:
            continue
        if isinstance(v, str):
            if v == "":
                continue
        if isinstance(v, dict):
            if not v:
                continue
        if isinstance(v, list):
            if not v:
                continue
        config[k] = v
    return config


def get_nested_dict(d: dict, key: str):
    for k in key.split("."):
        d = d.get(k)
        if d is None:
            return None
    return d
